package com.auto.learning.receiver;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.Handler;
import android.util.Log;

import com.auto.learning.MainActivity;
import com.auto.learning.bean.ResponeResult;
import com.auto.learning.event.BookNumChangeEvent;
import com.auto.learning.event.EventBus;
import com.auto.learning.event.listener.DialogListener;
import com.auto.learning.net.HttpCommonInfo;
import com.auto.learning.net.HttpRequestHelper;
import com.auto.learning.service.DownLoadService2;
import com.auto.learning.service.MusicPlayManager;
import com.auto.learning.service.PlayService;
import com.auto.learning.thread.pool.Pool;
import com.auto.learning.tools.CommonMethod;
import com.auto.learning.tools.TemporaryVariable;
import com.auto.learning.view.SharedPreferencesUtils;

public class NetCheckReceiver extends BroadcastReceiver {

	public static final String netACTION = "android.net.conn.CONNECTIVITY_CHANGE";
	public static final String closeNotify = "close_notify";
	
	private Context context;
	
	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 11:
			case 12:
				ResponeResult m_result = (ResponeResult) msg.obj;
				try {
					if (m_result != null) {
						JSONObject jsonObject = new JSONObject(m_result.getData());
						int isChange = jsonObject.getInt(HttpRequestHelper.BOOKNUM_ISCHANGED);  //1否2是
						int bookNum = jsonObject.getInt("bookNum");
						int userId = (int) SharedPreferencesUtils.getParam(context, HttpRequestHelper.USERID, 0);
						if (isChange == 2) {
							SharedPreferencesUtils.setParam(context,  userId + "_" + HttpRequestHelper.BOOKNUM_ISCHANGED, isChange);
							EventBus.getEventBus("readbook_num_change").post(new BookNumChangeEvent(bookNum, msg.arg1));
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				break;
			}
		};
	};

	@Override
	public void onReceive(final Context context, Intent intent) {
		this.context = context;
		if (intent.getAction().equals(netACTION)) {
			// true 代表网络断开     	   false 代表网络没有断开
			if (intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false)) {
				Log.d("NetCheckReceiver", true + ""); 
			} else {
				MusicPlayManager manager = MusicPlayManager.getInstance(context);
				int[] ids = manager.isPlayingBookId();
				if (ids[2] == 0 && !(boolean)SharedPreferencesUtils.getParam(context, HttpRequestHelper.DWONLOAD_PLAY_CONTINUE, false) && CommonMethod.getNetworkState(context) == 2 && !TemporaryVariable.downLoadedList.contains(ids[0])) {
					manager.setShowNetTips(false);
					manager.pause();
					CommonMethod.showMobileNetTips(TemporaryVariable.getTopActivity(), new DialogListener() {
						
						@Override
						public void otherButtonClick(Dialog dialog) {
							dialog.dismiss();
							HttpCommonInfo.M_NET_DIALOG_SHOW = false;
							MusicPlayManager.getInstance(context).setShowNetTips(true);
						}
						
						@Override
						public void okButtonClick(Dialog dialog) {
							dialog.dismiss();
							HttpCommonInfo.M_NET_DIALOG_SHOW = false;
							MusicPlayManager.getInstance(context).setShowNetTips(false);
							MusicPlayManager.getInstance(context).pause();
						}
						
						@Override
						public void cancelButtonClick(Dialog dialog) {
							MusicPlayManager.getInstance(context).setShowNetTips(true);
							dialog.dismiss();
							HttpCommonInfo.M_NET_DIALOG_SHOW = false;
						}
					});
				}else {
					manager.setShowNetTips(false);
				}
				
				//网络开启
				handler.postDelayed(new Runnable() {
					@Override
					public void run() {
						Pool.getPool().execute(new Runnable() {
							@Override
							public void run() {
								HttpRequestHelper.synchronousListenStatus(context, handler);  //同步数据到服务器
							}
						});
					}
				}, 10 * 1000);
			}
		}else if (closeNotify.equals(intent.getAction())) {
			try {
				while (!TemporaryVariable.activities.isEmpty()) {
					Activity activity = TemporaryVariable.activities.pop();
					if (activity != null) {
						activity.finish();
					}
				}
				context.stopService(new Intent(context,PlayService.class));
				context.stopService(new Intent(context, DownLoadService2.class));
			} catch (Exception e) {
				e.printStackTrace();
			}
			android.os.Process.killProcess(android.os.Process.myPid());
		}
	}
	
	
}
